<template lang="pug">
div
  template(v-if='!file')
    Upload(
      ref="upload"
      name='files[]'
      accept='video/mp4, audio/mp3'
      :show-upload-list="false"
      :format="['mp3', 'mp4']"
      :max-size="800"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      multiple
      type="drag"
      action='javascript:;'
      style="display: inline-block")
        div(style="width: 58px;height:58px;line-height: 58px;")
          Icon(type="plus" size="20")
  div(v-if='file')
    span {{ file.name }} &nbsp; &nbsp;
    Button(type='ghost', size='small', @click='doUpload', v-show='status === "normal"') 开始上传
    | &nbsp; &nbsp;
    Button(type='ghost', size='small', @click='reset', v-show='status === "normal"') 重新选择
    Button(type='ghost', size='small', @click='reset', v-show='status === "success"') 重新上传
    Progress(v-if='status !== "success"', :percent='percent', :status='status', style='width: 400px; display: block;')

</template>

<script>
// import { Wrapper as OSS } from 'ali-oss'
// import Api from '@/apis/app'
import OSS from '@/libs/oss'

// const ossConfig = {
//   region: 'oss-cn-hangzhou',
//   accessid: 'fklSF97boJxV9EzE',
//   accesskey: 'eXWoVbnNw1RJ2yMRq7fEWu2AgTI9Ng',
//   bucket: 'yfd-voice'
// }

export default {
  props: {
    defaultValue: {
      default: () => { return {} }
    }
  },
  data () {
    return {
      file: this.defaultValue.name ? this.defaultValue : null,
      percent: 0,
      status: this.defaultValue.name ? 'success' : 'normal'
    }
  },
  mounted () {
    // Api.getOssConfig(this.$store.state.app.id).then((data) => {
    //   this.callback = data.callback
    //   this.client = new OSS({
    //     region: ossConfig.region,
    //     accessKeyId: ossConfig.accessid,
    //     accessKeySecret: ossConfig.accesskey,
    //     bucket: ossConfig.bucket
    //   })
    // })
    OSS.getClient().then(({ client, config }) => {
      console.log(config)
      this.client = client
      this.config = config
    })
  },
  computed: {
    fileSize () { // mb
      return Math.floor(this.file.size / (1024 * 1024))
    }
  },
  methods: {
    handleBeforeUpload (file) {
      this.file = file
      // console.log(file.size / 1024 / 1024)
      return false
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 800k。'
      })
    },

    progress (p, cpt) {
      return (done) => {
        console.log(p, cpt)
        if (p === 1) {
          cpt && localStorage.removeItem(cpt.file.name)
          // this.status = 'success'
        } else {
          cpt && localStorage.setItem(cpt.file.name, JSON.stringify(cpt))
        }
        this.percent = Math.floor(p * 100)
        done()
      }
    },

    doUpload () {
      console.log(this.config)
      // var file = document.getElementById('file').files[0];
      // console.log(file)
      // return false
      // var key = document.getElementById('object-key-file').value.trim() || 'object';
      let key = this.config.dir + 'media/' + this.file.name
      console.log(this.file.name + ' => ' + key)

      let checkpoint = localStorage.getItem(this.file.name) || null
      checkpoint = JSON.parse(checkpoint)
      console.log('cp', checkpoint)
      if (checkpoint && ('file' in checkpoint)) {
        checkpoint.file = this.file
      }

      this.status = 'active'
      this.client.multipartUpload(key, this.file, {
        parallel: 4,
        partSize: 1024 * 1000, // 1kb * n
        checkpoint: checkpoint,
        progress: this.progress,
        headers: {
          'x-oss-callback': this.config.callback
        }
      }).then((res) => {
        console.log('upload success: ', res)
        this.status = 'success'
        // return listFiles(client);
        this.$emit('upload', res)
      })
    },

    reset () {
      this.file = null
      this.status = 'normal'
      this.percent = 0
    }

  }
}
</script>
